import * as XLSX from 'xlsx'

export function fileToBuffer(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(new Uint8Array(reader.result)); // 将 ArrayBuffer 转换为 Uint8Array (类似于 Buffer)
    };
    reader.onerror = () => {
      reject(reader.error);
    };
    reader.readAsArrayBuffer(file);
  });
}

export function readExcel(file) {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader()
    fileReader.readAsBinaryString(file)
    fileReader.onload = async function (ev) {
      try {
        let data = ev.target.result
        let workbook = XLSX.read(data, {
          type: 'binary'
        }) // 以二进制流方式读取得到整份excel表格对象
        let fromTo = ''
        let sheets = []
        // 遍历每张表读取
        for (let sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            fromTo = workbook.Sheets[sheet]['!ref']
            sheets.push(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]))
            break // 如果只取第一张表，就取消注释这行
          }
        }
        resolve(sheets[0]) // 解析结果
      } catch (e) {
        reject('文件格式有误')
      }
    }
  })
}
